# Bets Controller controls bet and challenge actions
# In 13wins, the user may place bets on sport matches using their WinPoints and also wager WinPoints to challenge their friends

class BetsController < ApplicationController
  # List bets in current streak 
  
  def hide_howto
   	current_user.hide_howto = true
   	current_user.save(false)
  end
  
  def index

    flash[:notice]= CGI.unescape(params[:notice]) if params[:notice]
    flash[:error]= CGI.unescape(params[:error]) if params[:error]

    @bets = current_user.current_streak_bets
    @bought_wins = BuyWin.find(:all,:conditions=>["user_id = ? and winstreak_id = ?  and point_config_id > 0",current_user.id,current_user.winstreak.id])
    if current_user.winstreaks.size > 1
      @last_winstreak_value = current_user.winstreaks[current_user.winstreaks.size-2].bets.win.sum(:winstreak_value)
      @last_bet = current_user.winstreaks[current_user.winstreaks.size-2].bets.last
    end
    unless params[:fb_sig_in_canvas]
      canvas_page_name = Facebooker.facebooker_config["canvas_page_name"]
      redirect_to "http://apps.facebook.com/#{@fb_name}/bets"
    end
  end

  # Create bets and redirect to corresponding url
  # If challenge, place bet
  # Record WinPoints history for bets and challenges
  def create
    @notice = ""
    @error  = ""
    placed  = false

   if chid = params[:accept]
    ch =  Challenge.find(chid)
    if ch.goter.point > ch.amount.to_i 
      ch.mode = "bet_1"
      ch.save
      ch.goter.point = ch.goter.point - ch.amount 
      ch.goter.save
      PointHistory.create(:user_id=>ch.goter.id,:action=>'Accepted a challenge on ' + ch.match.info,:point=>ch.amount,:earning => false)

    else
      @error = "Not enough WinPoints to accept this challenge. "
    end
   end

   # Place bet and send challenge
   if params[:to_user_id]
    place_amount = params[:amount].to_i > 500 ? 500 : params[:amount].to_i
    if User.find(params[:fb_sig_user]).point > place_amount + 50 and !Challenge.find(:first,:conditions=>["from_user_id=? and to_user_id =? and match_id = ?",params[:fb_sig_user],params[:to_user_id],params[:sid]])
      @to_user = User.find(params[:to_user_id])
      ch = Challenge.new
      ch.from_user_id = params[:fb_sig_user]
      ch.to_user_id   = params[:to_user_id]
      ch.amount       = place_amount 
      ch.match_id     = params[:sid]
      ch.message = params[:message]
      ch.mode         = "bet_0"
      ch.save
      ch.sender.point = ch.sender.point - ch.amount 
      ch.sender.save
      PointHistory.create(:user_id=>ch.sender.id,:action=>'Wagered a challenge on ' + ch.match.info,:point=>ch.amount,:earning => false)
       NotificationPublisher.deliver_challenge_notify(ch)
       NotificationPublisher.deliver_challenge_email(ch)
       placed = true
       @notice = "Challenge has been sent. " 
    else
       @error = "Not enough WinPoints to place this challenge." 
    end
   end

   # Place bet and accept challenge
   if params[:chid]
    ch = Challenge.find(params[:chid])
    if User.find(params[:fb_sig_user]).point > ch.amount + 50
      ch.mode         = "bet_1"
      ch.save
      ch.goter.point = ch.goter.point - ch.amount 
      ch.goter.save

      PointHistory.create(:user_id=>ch.sender.id,:action=>'Accepted a challenge on ' + ch.match.info,:point=>ch.amount,:earning => false)
       # NotificationPublisher.deliver_challenge_notify(ch)
       # NotificationPublisher.deliver_challenge_email(ch)
       placed = true
       @notice = "Challenge has been accepted. " 
    else
       @error = "You do not have enough WinPoints to accept this challenge. " 
    end
   end


    bets = Array(params[:bet]).compact
    valid_bet_size = bets.select{|b| b["team_id"].to_i > 0 and b["match_id"].to_i}.size 
    @sport = Sport.find(params[:sport_id]) if params[:sport_id]
    @success_saved_bets = []
    u = User.find(params[:fb_sig_user])
    if u.point >=  valid_bet_size * PointConfig.find_by_name("placebet_fee").point * -1 
     
      bets.each do |bet|
        @bet = current_user.bets.build(bet)
        # @bet.winstreak = current_user.winstreak
        if @bet.save
           @success_saved_bets << @bet 
        end
      end
       logs = Ilog.find(:all,:conditions=>["user_id = ?",current_user.id],:order=>'id desc',:limit=>2)
        last_log = logs.first
        last_log.no_of_bets += @success_saved_bets.size
        last_log.save
        @notice << "#{@success_saved_bets.size} bet(s) placed."
        u.point = u.point + PointConfig.find_by_name("placebet_fee").point * @success_saved_bets.size
        PointHistory.create(:user_id=>u.id,:action=>'Bet placed',:point=> - PointConfig.find_by_name("placebet_fee").point * @success_saved_bets.size,:earning => false)
        u.save
        #WinstreakPublisher.deliver_update_profile current_user unless @success_saved_bets.blank?

        # Publish actions now
        #current_user.publish_delayed_actions
    else
      @error << "You do not have enough WinPoints to place #{valid_bet_size} bet(s) "
      @error << "and make the challenge. " if !placed 
    end
    append = ""
    append += "?notice=" + @notice if @notice.size > 0 and @error.size == 0
    append += "?error=" + @error if @error.size > 0 and @notice.size == 0
    append = "?notice=" + @notice + "&error=" + @error if @error.size > 0 and @notice.size > 0
    flash[:notice] = @notice
    flash[:error ] = @error

    if @sport
      #redirect_to "http://apps.facebook.com/#{FB_NAME}/sports/" + @sport.id.to_s + append
      redirect_to "http://apps.facebook.com/#{FB_NAME}/bets/" + append
    else
      redirect_to "http://apps.facebook.com/#{FB_NAME}/bets" + append
    end
  end

  def history
  end

end
